package com.miracle.login.module.mvp.presenter;

import android.app.Activity;
import android.content.Context;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;

import com.miracle.basemvp.base.BasePresenter;
import com.miracle.basemvp.base.BaseResponse;
import com.miracle.basemvp.base.IPresenter;
import com.miracle.basemvp.lifecycle.rx.RxDefaultObserver;
import com.miracle.basemvp.network.download.ProgressDownloadListener;
import com.miracle.basemvp.network.download.RetrofitClient;
import com.miracle.common.bean.User.User;
import com.miracle.common.mvp.entity.request.CheckVersionRequest;
import com.miracle.common.mvp.entity.response.DandelionResponse;
import com.miracle.common.mvp.entity.response.VersionInfo;
import com.miracle.common.state.user.LoginContext;
import com.miracle.common.state.user.LoginState;
import com.miracle.common.util.PreferencesUtils;
import com.miracle.common.util.VersionUtil;
import com.miracle.login.module.mvp.contract.LoginContract;
import com.miracle.login.module.mvp.entity.request.LoginRequest;
import com.miracle.login.module.mvp.entity.response.LoginResponse;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.io.File;
import java.io.InputStream;

import javax.inject.Inject;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

import static com.miracle.common.CommonConfig.PGY_API_KEY;
import static com.miracle.common.CommonConfig.PGY_APP_KEY;

/**
 * com.miracle.login.module.mvp.presenter
 * (c)2018 AIR Times Inc. All rights reserved.
 *
 *
 * @author WangJQ
 * @version 1.0
 * @date 2018/6/29 16:28
 * @see com.miracle.login.module.mvp.presenter
 */
public class LoginPresenter extends BasePresenter<LoginContract.View, LoginContract.Model>
        implements IPresenter {

    @Inject
    public LoginPresenter(LoginContract.View view, LoginContract.Model model) {
        super(view, model);
    }

    public void login(LifecycleProvider<ActivityEvent> lifecycleProvider, final LoginRequest
            request) {

        boolean isNeedDialog = false;

        request.setUri("login");
        if (TextUtils.isEmpty(request.getJSESSIONID())) {
            isNeedDialog = true;
            request.setJSESSIONID("");
        } else {
            request.setUserName("");
            request.setPassWord("");
        }
        mModel.login(request)
                .compose(lifecycleProvider.<BaseResponse<User>>bindUntilEvent
                        (ActivityEvent.DESTROY))
                .subscribe(new RxDefaultObserver<BaseResponse<User>>((Activity)
                        mView, isNeedDialog) {
                    @Override
                    public void onSucceed(BaseResponse<User> response) {
                        LoginContext.getLoginContext().setUserState((Activity) mView, new
                                LoginState());
                        //自动登陆不再保存
                        if (TextUtils.isEmpty(request.getJSESSIONID())) {
                            LoginContext.getLoginContext().setUser((Activity) mView, response
                                    .getContent());
                        }
                        mView.loginSucc();
                    }
                });
    }

    /**
     * 检查版本
     * @param lifecycleProvider
     */
    public void checkVersion(LifecycleProvider<ActivityEvent> lifecycleProvider) {
        CheckVersionRequest request = new CheckVersionRequest();
        //当前版本号
        final int currVersion = VersionUtil.getLocalVersion(((Activity) mView));
        //设置蒲公英需要的api 和 app key
        request.set_api_key(PGY_API_KEY);
        request.setAppKey(PGY_APP_KEY);

        mModel.checkVersion(request)
                .compose(lifecycleProvider.<DandelionResponse<VersionInfo>>bindUntilEvent
                        (ActivityEvent.DESTROY))
                .subscribe(new Observer<DandelionResponse<VersionInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(DandelionResponse<VersionInfo>
                                               versionInfoDandelionResponse) {
                        if (versionInfoDandelionResponse.getCode().equals("0")) {
                            VersionInfo info = versionInfoDandelionResponse.getData();
                            if (info != null) {
                                try {
                                    int infoNo = Integer.parseInt(info.getBuildVersionNo());
                                    Log.d("WJQ", "newest version no is: " + infoNo);
                                    //保存当前服务器最新版本号到本地
                                    PreferencesUtils.setIntPreferences((Activity) mView,
                                            PreferencesUtils.Version.VERSION_NEWEST, infoNo);
                                    PreferencesUtils.setPreferences((Activity)mView, "url", info
                                            .getDownloadURL());
                                    if (currVersion < infoNo) {
                                        mView.FindANewVersion(info.getBuildUpdateDescription());
                                    } else {
                                        mView.NoNewVersion();
                                    }
                                } catch (NumberFormatException e) {
                                    mView.NoNewVersion();
                                }
                            }

                        } else {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void downloadApk(LifecycleProvider<ActivityEvent> lifecycleProvider, String url,
                            final ProgressDownloadListener listener) {
        url = PreferencesUtils.getPreferences(((Activity) mView), "url");
        //如果连接为空，那么退出
        if (TextUtils.isEmpty(url)) {
            listener.onFail("下载连接异常");
            return;
        }
        // 文件夹地址
        String filePath = Environment.getExternalStorageDirectory() + "/WeCloud";
        // 根据url获取文件
        File updateFile = new File(filePath);
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (!updateFile.exists()) {
            updateFile.mkdir();
        }
        String apkFullName = filePath + "/wecloud.apk";

        RetrofitClient.getInstance(listener)
                .downloadFiles(url, new Consumer<InputStream>() {
                    @Override
                    public void accept(InputStream fileInputStream) throws Exception {
                        listener.onFinishDownload();
                        Log.d("WJQ", "onFinish");
                    }
                }, apkFullName);
    }
}
